package filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebFilter("/LoginServlet")
public class LoginValidatorFilter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;
        HttpSession session = req.getSession();
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        String msg = "";
        if(userName != null) {
            if(userName.trim().length() > 20 || userName.trim().length() < 4 ){
                msg = msg + "用户名长度4-20位<br/>";
            }
        }
        if(password != null) {
            if(password.trim().length() > 20 || password.trim().length() < 4 ){
                msg = msg + "密码长度4-20位<br/>";
            }
        }
        if("".equals(msg)) {
            chain.doFilter(req, res);
        }else {
            session.setAttribute("msg", msg);
            res.sendRedirect(req.getHeader("referer"));
        }
    }
}
